// 弹出框
/**    弹出框Map,key为下标，value为dialog对象
@type Map
*/
Touchjs.dialogs = new ShieldMap();
Touchjs.dialog = {
	/**    弹出框元素对象
    @type jQueryObject
     */
    dialogO : null, //当前弹出框Dialog对象
    init : function (ele, index, title, width, height, preEle, preEleIndex, onlyOne){
        var dialog = new Dialog();
        dialog.init(ele, index, width, height, preEle, preEleIndex);
        dialog.title = title;
        this.dialogO = dialog;
        Touchjs.dialogs.put(index, dialog);
    },
    removeCallback : function(dialogE) {
        // 具体实现中扩展
    },
    /**    重置宽高
     * @type jQueryObject */
    resize : function(layerIndex, layerInitWidth, layerInitHeight) {
        if (!layerInitWidth) {
            var perDialog = Touchjs.dialogs.get(layerIndex);
            if (perDialog && perDialog.ele) {
                layerInitWidth = perDialog.ele.width(); //获取元素的宽度
            }
        }
        var docWidth = $(window).width(); //可视区域，document为全部区域
        var docHeight = $(window).height(); //可视区域，document为全部区域
        var minWidth = layerInitWidth > docWidth ? docWidth : layerInitWidth;  
        var minHeight = layerInitHeight > docHeight ? docHeight : layerInitHeight;
//            console.log("resize"+layerIndex+" "+layerInitWidth+" "+ layerInitHeight+" "+docWidth+" "+docHeight);
        var style = {height:layerInitHeight, width: layerInitWidth};
        if (layerInitHeight > docHeight) {
            style.top = 5;
            style.height = minHeight -10;
        } else if (layerInitWidth > docWidth) {
            style.width = minWidth;
        }
        this.width = style.width;
        this.heigth = style.height;
        layer.style(layerIndex, style);
    },
    /**    打开弹出框
     * @param title {String} 弹出框标题
     * @param htmlContent {String} 弹出框内容
     * @param success {Function} 加载完成后的回调方法
     * @param width {Number} 弹出框宽度
     * @param height {Number} 弹出框高度
     * @param relType {String} 关联类型，可以为iframe或者不填
     * @param options {Json} 扩展属性
     */
	open : function(title, htmlContent, success, width, height, relType, options){
		var dialog= this;
        if(typeof layer == "undefined" ){
        	Touchjs.error("缺少依赖JS库：layer！");
            return false;
        }
        var optionsJson = Touchjs.data2JsonObj(width); // success后直接跟了options
        if (optionsJson) {
        	options = width;
        	width = null;
        	height = null;
        	relType = null;
        }
        
        
        var openType = 1;
        if (relType && relType=="iframe") {
            openType = 2;
        }
		if (!$.isFunction(success)) {
			options = success;
			success = null;
        }
		if (options == null) {
			options = {};
        }
		var onlyOne = options.onlyOne||false;
		if (openType != 2) { //非iframe,iframe待实现
			var winHeight = $(window).height();
			var ops = {
				type: openType,  //可传入的值有：0（信息框，默认）1（页面层）2（iframe层,content位url）3（加载层）4（tips层）
				skin: 'shieldjs-custom-layer', //自定义样式
				maxHeight : winHeight-14, //最大高度，只有当高度自适应时，设定才有效。
				area: (width ? width : 500)+'px', //宽度，高度自适应
				title: title,
				content: htmlContent,
				success: function (layero, index) {
					var ele = $(layero);
					ele.addClass("shieldjs-touch-dialog-opened")
					ele.data("dialog-index", index);
					Touchjs.touch(ele); //继续加载
					if(success && $.isFunction(success)){
						success(ele, index)
					}
					/*if (Touchjs.touch) {
                       Touchjs.touch(ele);
                   	}*/
				},
				cancel: function(index, layero){
					var ele = $(layero);
					// 自定义的关闭方法
					if(options.close && $.isFunction(options.close)){
						options.close(index, ele);
					}
					dialog.close();
					return true; 
				}
			};
			options = $.extend(true, ops, options);
			var index = layer.open(options);
			
			dialog.init($('#layui-layer'+index), index, title, null, null, Touchjs.dialogE, dialog.dialogO?dialog.dialogO.index:null, onlyOne); //初始化
            Touchjs.dialogE = dialog.dialogO.ele;
            
            var dialogContentE = dialog.dialogO.ele.find(".layui-layer-content");
            var titleHeight = dialog.dialogO.ele.find(".layui-layer-title").height();
            /*自身内容发生变化时，layui-layer-content为dialog的内容区*/
            dialogContentE.resize(function() {
                console.log(dialogContentE[0].scrollHeight+titleHeight);
                setTimeout(function(){
                    dialog.resize(index, null, dialogContentE[0].scrollHeight+titleHeight); //调用resize方法
                }, 100);    
            });
                
            /*windows窗口变化时重置大小*/
            Touchjs.winResizes["dialogResize"+index] = function() { //宽度处理有问题
//                    console.log("resize"+index+" "+dialog.dialogO.ele.width()+" "+ dialog.dialogO.ele.height()+" scroll:"+ dialog.dialogO.ele.find(".layui-layer-content")[0].scrollHeight );
                // Touchjs.dialogE.find(".layui-layer-content")[0].scrollHeight 为div的实际高度，如有滚动条时获取真实高度
                dialog.resize(index, null, dialogContentE[0].scrollHeight+titleHeight); //调用resize方法 
            };
		}
	},
	close : function(indexV) {
		var dialogIndex = null;
		if (this.dialogO) {
			dialogIndex = this.dialogO.index;
        }
        if (indexV) {
            dialogIndex = indexV;
        }
        if (dialogIndex) {
        	var dialogObj = Touchjs.dialogs.get(dialogIndex);
        	Touchjs.winResizes["dialogResize"+dialogIndex] = null; //resize置空
            
        	var curDialogE = Touchjs.dialogE;
        	if (curDialogE.data("extendRemove")) {
        		curDialogE.data("extendRemove")(indexV, curDialogE);
        	}
        	Touchjs.dialog.removeCallback(curDialogE);
        	console.log(new Date()+"remove dialog"+" "+dialogIndex);
        	if (dialogObj) {
        		Touchjs.dialogE = dialogObj.preEle;
        		var index = dialogObj.preEleIndex;
        		var perDialog = Touchjs.dialogs.get(index);
        		this.dialogO = perDialog;
        	} else {
        		Touchjs.dialogE = null;
        		this.index = -1;
        		this.dialogO = null;
        	}
        	if (dialogObj && dialogObj.index) {
        		Touchjs.dialogs.remove(dialogObj.index);
        		layer.close(dialogObj.index); //此时你只需要把获得的index，轻轻地赋予layer.close即可
        	} else {
        		var indexNew = layer.index; //以为提示也用了layer，所以其实比真实index多了1
        		Touchjs.dialogs.remove(indexNew);
        		layer.close(indexNew-1); //它获取的始终是最新弹出的某个层，值是由layer内部动态递增计算的
        	}
        }
    }
};
/**    打开弹出框(实际调用的是dialog.open)
 * @param title {String} 弹出框标题
 * @param htmlContent {String} 弹出框内容
 * @param success {Function} 加载完成后的回调方法
 * @param width {Number} 弹出框宽度
 * @param height {Number} 弹出框高度
 * @param relType {String} 关联类型，可以为iframe或者不填
 * @param options {Json} 扩展属性
*/
Touchjs.openDialog = function(title, htmlContent, success, width, height, relType, options) {
	options = options||{};
	Touchjs.dialog.open(title, htmlContent, success, width, height, relType, options);
}
/**    根据标题获取弹出框，结果为数组
* @param title {String} 标题
  @returns {Array}  Dialog对象数组  */
Touchjs.getDialogs = function(title) {
	var dialogsGet = new Array();
	for(var dialog in Touchjs.dialogs.values()){
	    if (dialog.title == title) {
	        dialogsGet.push(dialog); //添加到 dialogsGet 的尾部
	    }
	}
	return dialogsGet;
}